<?php

require_once 'Machine.php';
require_once 'Util.php';
require_once 'DBManager.php';
require_once 'Zend/Log.php';
require_once 'Zend/Debug.php';
require_once 'Zend/Log/Writer/Stream.php';
require_once 'Zend/Config/Ini.php';

define(CONFIGURATION_FILE, 'config/daemon.ini');
define(APPLICATION_ENV, 'development');

class ControlStatus {

    private $log;
    private $dbAccess;

    public function __construct() {
        $config = new Zend_Config_Ini(CONFIGURATION_FILE, APPLICATION_ENV);
        $writer = new Zend_Log_Writer_Stream($config->get('control_status_logfile'));
        $this->log = new Zend_Log($writer);
        $this->dbAccess = new DBManager($this->log);
        $this->log->debug("Connected to database...");
    }

    public function refreshvmAction() {
        $vmAcademicoDao = new Machine($this->log, $this->dbAccess);
        $vms = $this->getVMWithAjobId();
        $rest = new Util();
        foreach ($vms as $vm) {
            $response = $rest->jobStatus($vm['async_job_id'], $this->log);
            $this->log->debug(print_r($response, true));
            if (isset($response['queryasyncjobresultresponse']['errorcode'])) {
                $data = array('estado' => 'E', 'async_job_id' => '');
                $vmAcademicoDao->save($data, array('key' => 'codigo_maquina_virtual', 'value' => $vm['codigo_maquina_virtual']));
                $this->log->debug("error ocurred");
            } else if (isset($response['queryasyncjobresultresponse']['jobresult']['errorcode'])) {
                $data = array('estado' => 'E', 'async_job_id' => '');
                $vmAcademicoDao->save($data, array('key' => 'codigo_maquina_virtual', 'value' => $vm['codigo_maquina_virtual']));
                $this->log->debug("error ocurred");
            } else if (isset($response['queryasyncjobresultresponse']['jobresult']['virtualmachine']['id'])) {

                $data = array('codigo_vm' => $response['queryasyncjobresultresponse']['jobresult']['virtualmachine']['id'], 'estado' => 'A', 'async_job_id' => '');
                $vmAcademicoDao->save($data, array('key' => 'codigo_maquina_virtual', 'value' => $vm['codigo_maquina_virtual']));
                $this->log->debug("[ id ] {$response['queryasyncjobresultresponse']['jobresult']['virtualmachine']['id']}");
            }
        }
    }

    /**
     * 
     * @param type $codigoVM
     * @return type
     * @throws Exception
     */
    public function getVMWithAjobId() {
        try {
            $select = $this->dbAccess->getDb()->select()->from(Machine::TABLE_NAME)
                    ->where("async_job_id != ''");
            return $this->dbAccess->getDb()->fetchAll($select);
        } catch (Exception $e) {
            throw $e;
        }
    }

}

//  mail
$controlStatus = new ControlStatus();
$controlStatus->refreshvmAction();
?>
